import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class EmployeeManager {
    private static final String FILE_PATH = "employees.dat";

    public static void main(String[] args) {
        // 创建三个员工对象
        Employee emp1 = new Employee("张三", 25, 5000.0);
        Employee emp2 = new Employee("李四", 30, 6000.0);
        Employee emp3 = new Employee("王五", 35, 7000.0);

        // 添加员工到文件
        List<Employee> employees = new ArrayList<>();
        employees.add(emp1);
        employees.add(emp2);
        employees.add(emp3);

        saveEmployeesToFile(employees);

        // 从文件读取并打印员工信息
        List<Employee> loadedEmployees = loadEmployeesFromFile();
        printEmployees(loadedEmployees);
    }

    public static void saveEmployeesToFile(List<Employee> employees) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_PATH))) {
            oos.writeObject(employees);
            System.out.println("员工信息已成功保存到文件");
        } catch (IOException e) {
            System.err.println("保存员工信息到文件时出错: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    public static List<Employee> loadEmployeesFromFile() {
        List<Employee> employees = new ArrayList<>();
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_PATH))) {
            employees = (List<Employee>) ois.readObject();
        } catch (FileNotFoundException e) {
            System.err.println("文件不存在: " + e.getMessage());
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("从文件读取员工信息时出错: " + e.getMessage());
        }
        return employees;
    }

    public static void printEmployees(List<Employee> employees) {
        System.out.println("员工信息列表:");
        for (Employee emp : employees) {
            System.out.println(emp);
        }
    }
}    